package com.lagou.builder;

import com.lagou.config.Configuration;
import com.lagou.io.Resource;
import com.lagou.mapping.MappedStatement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        //数据源
        DataSource dataSource = parseDatasource(rootElement);
        configuration.setDataSource(dataSource);
        List<Element> mappers = rootElement.selectNodes("//mapper");
        for (Element mapper : mappers) {
            String mapperPath = mapper.attributeValue("resource");
            InputStream mapperStream = Resource.getResourceAsStream(mapperPath);
            new XMLMapperBuilder(configuration).parse(mapperStream);
        }
        return  configuration;
    }

    private DataSource parseDatasource(Element rootElement) throws PropertyVetoException {
        List<Element> list = rootElement.selectNodes("dataSource");
        Element element = list.get(0);

        //读取配置信息
        Properties properties = parseProperties(element);

        ComboPooledDataSource  dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        return dataSource;
    }

    private Properties parseProperties(Element element) {
        List<Element> propertiesElement = element.selectNodes("property");
        Properties properties= new Properties();
        for (Element e : propertiesElement) {
            properties.put(e.attributeValue("name"),e.attributeValue("value"));
        }
        return properties;
    }
}
